<template>
  <div class="addEditArticlePageCont">
    <div class="addEditArticlePageMian">
      <div class="allBox">
        <div class="tempPe">
          <div class="tit">模板预览</div>
          <div class="titX" v-if="tempFlag && currentIndex === 0 && noEg">
            <span>
              样例来源：{{ exampVal?.companyName }}-{{ exampVal?.buildingName }}，已有{{
                exampVal?.scanCount
              }}个客户扫码
            </span>
            <span @click="shortArticleSample">换一个灵感</span>
          </div>
          <div class="tempBox">
            <div class="screenBox" v-if="tempFlag">
              <div class="screenBox1">
                <!-- <dt-loading :loadSmall="true" :loading="loadSmallFlag"></dt-loading> -->
                <screen-temp ref="screenTemp" @uploadSuccess="uploadSuccess"></screen-temp>
              </div>
            </div>
            <div class="noChoose" v-if="!tempFlag">
              {{ muText }}
            </div>
          </div>
          <carousel ref="carousel" @tempChoose="tempChoose" />
        </div>
        <div class="formBox">
          <Form ref="form" :model="editorInfo" :rules="rules" :label-width="150">
            <FormItem label="标题：" prop="titleRichText">
              <dt-editor
                v-model="editorInfo.titleRichText"
                :type="'toolbarList4'"
                @getEdit="getEdit"
                :height="120"
                :maxLength="50"
                @onEditorChange="onEditorChange"></dt-editor>
            </FormItem>
            <div class="min" v-if="titleSensitiveWords">
              <FormItem label="敏感词汇：">
                <div class="wrong">
                  {{ titleSensitiveWords }}
                </div>
              </FormItem>
            </div>
            <span class="checkFlag">
              <Checkbox v-model="editorInfo.hidden" novalidate>隐藏标题（标题不在霸屏神器中展示）</Checkbox>
            </span>
            <FormItem label="内容：" style="margin-top: 14px">
              <dt-editor
                v-model="editorInfo.contentRichText"
                :type="'toolbarList3'"
                :maxLength="500"
                @onEditorChange="onEditorChange1"
                :height="150"></dt-editor>
            </FormItem>
            <div class="min" v-if="sensitiveWords">
              <FormItem label="敏感词汇：">
                <div class="wrong">
                  {{ sensitiveWords }}
                </div>
              </FormItem>
            </div>
            <FormItem label="配图：" class="FormItemUpload" style="margin-top: 14px">
              <div class="demo-upload-list" v-for="(item, index) in editorInfo.fileList" :key="index">
                <img :src="item.url" />
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                  <Icon type="ios-trash-outline" @click="handleRemove(index)"></Icon>
                </div>
              </div>
              <Upload
                ref="upload"
                v-if="editorInfo.fileList.length > 0 ? false : true"
                :show-upload-list="false"
                :data="upload.data"
                name="multipartFile"
                :headers="upload.headers"
                :max-size="10240"
                :format="['jpg', 'png', 'jpeg']"
                type="drag"
                :on-format-error="handleFormatError"
                :before-upload="beforeUpload"
                :action="upload.reqUrl"
                style="display: inline-block; width: 58px">
                <div style="width: 58px; height: 58px; line-height: 58px">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
              <span
                class="imageSize"
                v-if="editorInfo.fileList.length > 0 ? true : false"
                @click="agingUpload">
                重新裁剪
              </span>
              <span class="imageText" v-else>jpg、png、jpeg格式</span>
            </FormItem>
            <FormItem label="扫码落地页:">
              <span style="color: #999">（您可指定客户在霸屏神器中扫描二维码后所进入的页面）</span>
              <Select v-model="editorInfo.scanCodeType" disabled>
                <Option value="ONLINE_SALE_OFFICE">线上售楼处</Option>
              </Select>
            </FormItem>
            <div class="exampClass">
              <span
                :class="{ active: index === currentIndex }"
                v-for="(item, index) in exampleList"
                :key="index"
                @click="exampleClick(index)">
                {{ item.title }}
              </span>
            </div>
            <FormItem label="朋友圈文案：">
              <div style="color: #999">（您可预先编辑朋友圈文案，以方便顾问在分享霸屏神器时快速复制）</div>
              <div class="wxText">
                <div style="width: 50%">
                  <Input
                    v-model="editorInfo.wxContent"
                    maxlength="500"
                    :autosize="{ minRows: 5 }"
                    show-word-limit
                    type="textarea"
                    placeholder="请输入微信文案..." />
                </div>
                <div class="wxTextVal">
                  <span>参考示例：</span>
                  <br />
                  🌊|同策壹号公馆 环湖首排正席|💎 🔥 | 6月18日 建档盛启 | 🔥 ———「 同策壹号 」——— 🏡约𝟵𝟵-𝟭𝟰𝟯㎡
                  | 湾心传世美宅 ✆888-88888 888宝藏地块 首开在即
                </div>
              </div>
            </FormItem>
            <FormItem label="同步至线上售楼处：">
              <i-switch size="large" v-model="editorInfo.saleOffice">
                <span slot="open">ON</span>
                <span slot="close">OFF</span>
              </i-switch>
              <span style="display: block; color: #999">
                您可将霸屏神器中的内容在线上售楼处中同步展示，以丰富线上售楼处的内容
              </span>
            </FormItem>
            <div class="footer">
              <Button @click="addEditArticleReset" style="margin-left: 8px">取消</Button>
              <Button type="primary" @click="preViewScreen" style="margin-left: 8px">立即发布</Button>
            </div>
          </Form>
        </div>
      </div>
    </div>
    <dt-cropper ref="dtCropper" @success="getCropper" />
    <dt-loading :loading="loadingFlag"></dt-loading>
    <preview-image
      :images="preViewImg"
      :showDownLoad="showDownLoad"
      :showIndex="showIndex"
      :showBtn="showBtn"
      okText="立即发布"
      @prevImgEmit="prevImgEmit"
      @prevImgCancel="prevImgCancel"
      ref="preViewImage"></preview-image>
    <Modal v-model="leaveModal" title="离开" :footer-hide="true">
      <p class="footer1Text">当前内容尚未保存，离开后将清空所填写的内容，是否要离开？</p>
      <div class="footer1">
        <Button @click="leave" style="margin-left: 8px">离开</Button>
        <Button type="primary" @click="leaveCancel" style="margin-left: 8px">暂不离开</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import toolMgr from '@/biz/base/tool.js'
  import bgMapMgr from '@/biz/bgMap/bgMap'
  import screenTemp from '@/components/screenTemp/screenTemp'
  import carousel from './components/carousel.vue'
  import 'quill/dist/quill.snow.css'
  export default {
    components: {
      screenTemp,
      carousel
    },
    data() {
      let vm = this
      return {
        noEg: false,
        muText: '您可以在下方挑选一个模版来创作霸屏神器',
        scaleVal: ['4:3', '3:4', '1:1', 'no'],
        leaveModal: false,
        currentIndex: 0,
        exampleList: [
          {
            title: '查看样例'
          },
          {
            title: '预览效果'
          }
        ],
        showBtn: true,
        loadingFlag: false,
        upload: toolMgr.unloadImage(),
        preViewImg: [],
        showIndex: 0,
        showDownLoad: false,
        editorInfo: {
          hidden: false,
          title: '',
          titleRichText: '',
          content: '',
          contentRichText: '',
          fileList: [],
          scanCodeType: 'ONLINE_SALE_OFFICE',
          saleOffice: false,
          wxContent: ''
        },
        rules: {
          titleRichText: [{ required: true, message: '请输入霸屏神器标题', trigger: 'change' }]
        },
        titleSensitiveWords: '',
        sensitiveWords: '',
        tempFlag: false,
        screenThree: {
          contentRichText:
            '请输入正文内容，请输入正文内容，请输入正文内容，请输入正文内容，请输入正文内容，请输入正文内容请输入正文内容，请输入正文内容，请输入正文内容',
          picClipUrl: 'https://static.tospurfang.com/dt-management/activity/placeholder.png',
          titleRichText: '请输入标题，请输入标题，请输入标题',
          hidden: false
        },
        screenThreeOld: {},
        exampVal: {},
        templateId: '',
        imgWH: {},
        leveFlag: false,
        nextVal: '',
        editDom: ''
      }
    },
    watch: {
      editorInfo: {
        handler(newValue, oldValue) {
          if (this.currentIndex == 1) {
            let threeVal = {
              contentRichText: this.editorInfo.contentRichText,
              picClipUrl: this.editorInfo.fileList[0]?.url,
              titleRichText: this.editorInfo.titleRichText,
              hidden: this.editorInfo.hidden
            }

            this.$store.dispatch('screenThree', threeVal)
          }
        },
        deep: true
      }
    },
    methods: {
      getEdit(val) {
        this.editDom = val
        this.editDom.format('resize', '26px')
        this.editDom.format('bold', true)
      },
      prevImgCancel() {
        if (this.currentIndex == 0) {
          this.$store.dispatch('screenThree', this.screenThreeOld)
        }
      },
      leaveCancel() {
        this.leaveModal = false
      },
      leave() {
        this.leaveModal = false
        this.leveFlag = true
        if (typeof this.nextVal === 'function') {
          this.nextVal()
        } else {
          this.$router.push({
            path: '/marketingCenter/shortArticle'
          })
        }
      },
      exampleClick(val) {
        if (val === 1 && this.editorInfo.titleRichText == '') {
          this.$Message.warning('请填写标题')
          return false
        }
        this.currentIndex = val
        if (val === 0) {
          if (Object.keys(this.screenThreeOld).length === 0) {
            this.shortArticleSample()
          } else {
            this.$store.dispatch('screenThree', this.screenThreeOld)
          }
        } else {
          let threeVal = {
            contentRichText: this.editorInfo.contentRichText,
            picClipUrl: this.editorInfo.fileList[0]?.url,
            titleRichText: this.editorInfo.titleRichText,
            hidden: this.editorInfo.hidden
          }
          this.$store.dispatch('screenThree', threeVal)
        }
      },
      // 样例
      shortArticleSample() {
        this.loadingFlag = true
        let params = {
          templateId: this.templateId,
          buildingId: this.$dt.buildInfo().housesId
        }
        bgMapMgr.getShortArticleSample(params).then((res) => {
          if (res) {
            this.noEg = true
            this.exampVal = res
            this.screenThree.contentRichText = res.contentRichText
            this.screenThree.picClipUrl = res.picClipUrl
            this.screenThree.titleRichText = res.titleRichText
            this.screenThree.hidden = res.hidden
            this.screenThreeOld = this.$tool.deepClone(this.screenThree)
            this.$store.dispatch('screenThree', this.screenThree)
          } else {
            this.noEg = false
            let screenThree1 = {
              contentRichText:
                '请输入正文内容，请输入正文内容，请输入正文内容，请输入正文内容，请输入正文内容，请输入正文内容请输入正文内容，请输入正文内容，请输入正文内容',
              picClipUrl: 'https://static.tospurfang.com/dt-management/activity/placeholder.png',
              titleRichText: '请输入标题，请输入标题，请输入标题',
              titleCalss: true
            }
            this.$store.dispatch('screenThree', screenThree1)
          }
          this.$nextTick(() => {
            this.loadingFlag = false
          })
        })
      },

      //选择模板
      tempChoose(item) {
        if (item) {
          this.tempFlag = true
          this.templateId = item.id

          if (this.currentIndex == 0) {
            this.shortArticleSample()
          } else {
            let threeVal = {
              contentRichText: this.editorInfo.contentRichText,
              picClipUrl: this.editorInfo.fileList[0]?.url,
              titleRichText: this.editorInfo.titleRichText,
              hidden: this.editorInfo.hidden
            }
            this.$store.dispatch('screenThree', threeVal)
          }

          this.$store.dispatch('screenInfo', item)
        } else {
          this.muText = '之前选择的模版已经下架，请重新选择模版'
        }
      },
      // 富文本
      onEditorChange(val) {
        if (val.html == '') {
          setTimeout(() => {
            this.editDom.format('resize', '26px')
            this.editDom.format('bold', 'bold')
          })
        }
        this.editorInfo.title = val.text
      },
      onEditorChange1(val) {
        this.editorInfo.content = val.text
      },

      // 裁剪
      agingUpload() {
        this.$refs.dtCropper.show({ file: this.oldFile, scaleVal: this.scaleVal })
      },
      getCropper(val) {
        if (val) {
          let params = [
            {
              url: val,
              name: new Date().getTime()
            }
          ]
          this.editorInfo.fileList = params
          setTimeout(() => {
            this.loadingFlag = false
          }, 500)
        }
      },

      // 预览大图
      uploadSuccess(val) {
        if (val == false) {
          this.loadingFlag = false
          this.$Message.warning('发布失败请重新发布')
        } else if (val === 'success') {
          this.saveSc()
        } else {
          this.loadingFlag = false
          this.preViewImg = []
          this.preViewImg.push(val)
          this.$refs.preViewImage.show()
        }
      },
      //预览后的保存
      saveSc() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId, //模板id
          templateId: this.templateId, //模板id
          title: this.editorInfo.title,
          titleRichText: this.editorInfo.titleRichText,
          content: this.editorInfo.content,
          contentRichText: this.editorInfo.contentRichText,
          picClipUrl: this.editorInfo.fileList[0]?.url,
          picUrl: this.editorInfo.fileList[0]?.url,
          scanCodeType: this.editorInfo.scanCodeType,
          wxContent: this.editorInfo.wxContent,
          saleOffice: Number(this.editorInfo.saleOffice),
          previewUrl: this.$store.state.screenImg,
          previewAppUrl: this.$store.state.screenAppImg,
          previewConciseUrl: this.$store.state.screenAppImgNoName,
          previewWidth: this.imgWH.imageWidth,
          previewHeight: this.imgWH.imageHeight
        }

        if (this.$route.query.type == 'edit') {
          params.id = this.$route.query.id
          bgMapMgr
            .shortSrticleUpdateById(params)
            .then((res) => {
              if (res.sensitiveValid == 1) {
                this.loadingFlag = false
                this.leave()
              } else {
                this.loadingFlag = false
                this.sensitiveWords = res.sensitiveWords
                this.titleSensitiveWords = res.titleSensitiveWords
                this.$Message.warning('请修改敏感词汇后提交')
              }
            })
            .catch((err) => {
              this.loadingFlag = false
              this.$Message.error(err)
            })
        } else {
          bgMapMgr
            .shortSrticleSave(params)
            .then((res) => {
              if (res.sensitiveValid == 1) {
                this.loadingFlag = false
                this.leave()
              } else {
                this.loadingFlag = false
                this.sensitiveWords = res.sensitiveWords
                this.titleSensitiveWords = res.titleSensitiveWords
                this.$Message.warning('请修改敏感词汇后提交')
              }
            })
            .catch((err) => {
              this.loadingFlag = false
              this.$Message.error(err)
            })
        }
      },
      prevImgEmit(val) {
        this.imgWH = val
        this.loadingFlag = true
        setTimeout(() => {
          this.$refs.screenTemp.show(true, 'two')
        }, 100)
      },
      // 立即发布展示预览
      preViewScreen() {
        if (!this.tempFlag) {
          return this.$Message.warning('请选择模板')
        }
        this.showBtn = true
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.screenThree.contentRichText = this.editorInfo.contentRichText
            this.screenThree.picClipUrl = this.editorInfo.fileList[0]?.url
            this.screenThree.titleRichText = this.editorInfo.titleRichText
            this.screenThree.hidden = this.editorInfo.hidden

            console.log(this.screenThree, 'this.screenThree')
            this.$store.dispatch('screenThree', this.screenThree)
            this.loadingFlag = true
            setTimeout(() => {
              this.$refs.screenTemp.show(false)
            }, 100)
          }
        })
      },

      // // form 表单
      addEditArticleReset() {
        this.leaveModal = true
      },
      // 文件格式验证失败
      handleFormatError(file) {
        this.$Message.warning('图片格式只支持jpg,png格式！')
      },
      // 上传前
      beforeUpload(file) {
        const isJpg = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 10

        if (!isJpg && !isPng) {
          this.$Message.error('只能上传 JPG 或 PNG 格式的图片')
          return false
        }
        if (!isLt2M) {
          this.$Message.error('图片大小不能超过 10MB')
          return false
        }
        this.oldFile = file
        this.$refs.dtCropper.show({ file: this.oldFile, scaleVal: this.scaleVal })
        return false
      },
      handleView(val) {
        this.showBtn = false
        this.preViewImg = [val]
        this.$refs.preViewImage.show()
      },
      handleRemove(index) {
        this.editorInfo.fileList.splice(index, 1)
      },
      async convertImageUrlToFile(imageUrl) {
        try {
          const response = await fetch(imageUrl)
          if (!response.ok) {
            throw new Error('网络错误')
          }
          const blob = await response.blob()
          let typeVal = imageUrl.split('.')[imageUrl.split('.').length - 1]
          const file = new File([blob], 'image.jpg', { type: 'image/' + typeVal == 'jpg' ? 'jpeg' : typeVal })
          return file
        } catch (error) {
          console.error('转换图片URL为File对象时出错：', error)
        }
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.leveFlag) {
        next()
      } else {
        this.leaveModal = true
        this.nextVal = next
      }
    },
    mounted() {
      if (this.$route.query.type == 'add') {
      } else if (this.$route.query.type == 'edit') {
        bgMapMgr
          .shortSrticleGetById({ id: this.$route.query.id })
          .then((res) => {
            if (res) {
              this.editorInfo.fileList = res.picClipUrl ? [{ url: res.picClipUrl }] : []
              this.convertImageUrlToFile(res.picClipUrl).then((r) => {
                this.oldFile = r
              })

              this.editorInfo.titleRichText = res.titleRichText
              this.editorInfo.contentRichText = res.contentRichText
              this.editorInfo.hidden = res.hidden
              this.editorInfo.scanCodeType = res.scanCodeType
              this.currentIndex = 1
              this.editorInfo.wxContent = res.wxContent
              this.editorInfo.saleOffice = res.saleOffice ? true : false

              this.$refs.carousel.getTemplateId(res.templateId)
            }
          })
          .catch((err) => {
            this.$Message.error(err)
          })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .addEditArticlePageCont {
    * {
      box-sizing: border-box;
    }
    height: 100%;
    .title {
      background-color: #f5f5f5;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
      padding: 0 14px 10px;
    }

    .addEditArticlePageMian {
      padding-top: 16px;
      height: 100%;
      position: relative;
      .allBox {
        display: flex;
        flex-direction: row;
        padding: 0 10px;
        height: 100%;
        .tempPe {
          width: 40%;
          border: 1px #ccc solid;
          padding: 10px;
          height: 100%;
          min-width: 400px;
          .tit {
            font-size: 20px;
            font-weight: bold;
          }
          .titX {
            background-color: #c1e0ff;
            padding: 5px 10px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            span:last-child {
              color: #0080ff;
              cursor: pointer;
            }
          }
        }
        .tempBox {
          // height: 500px;
          height: calc(100% - 200px);
          overflow: hidden;
          padding: 10px 0;

          .screenBox {
            height: 100%;

            overflow-y: scroll;
            .screenBox1 {
              position: relative;
              width: 375px;
              margin: 0 auto;
            }
          }
          .noChoose {
            text-align: center;
            font-weight: bold;
            padding-top: 200px;
          }
        }
        .formBox {
          width: 60%;
          padding: 10px 20px 50px;
          border: 1px #ccc solid;
          margin-left: 5px;
          height: 100%;
          overflow-y: scroll;

          .checkFlag {
            display: block;
            margin-left: 140px;
            margin-top: 20px;
          }
        }
      }
    }

    .ivu-form-item {
      margin-bottom: 10px;
    }

    .check1 {
      height: 40px;
      padding-left: 130px;
      color: #ed4014;
    }
  }
  .exampClass {
    width: 400px;
    margin: 20px auto;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    span {
      border: 1px solid #999;
      padding: 5px 40px;
      border-radius: 5px;
      cursor: pointer;
    }
    span.active {
      background: #2d8cf0;
      color: #fff;
    }
  }

  .footer {
    text-align: center;
    position: fixed;
    padding: 10px 0;
    bottom: 0;
    right: 0;
    width: 300px;
    background-color: #fff;
    z-index: 999;

    button {
      margin: 0 10px;
    }
  }
  .footer1Text {
    padding: 20px 0;
  }
  .footer1 {
    text-align: center;
    margin: 20px 0;
    button {
      margin: 0 10px;
    }
  }

  // 上传
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .FormItemUpload .ivu-form-item-contentRichText {
    display: flex;
  }

  .imageSize {
    display: inline-block;
    margin-left: 16px;
    vertical-align: top;
    padding-top: 16px;
    font-size: 12px;
    color: #2d8cf0;
    cursor: pointer;
  }

  .imageText {
    display: inline-block;
    margin-left: 16px;
    vertical-align: top;
    padding-top: 16px;
    font-size: 12px;
    color: #999;
  }
  .wxTextVal {
    flex: 1;
    background-color: #eee;
    border: 1px #ccc solid;
    padding: 5px;
    margin-left: 5px;
    line-height: 1.5;
  }
  .wrong {
    color: red;
  }
  .swperClick {
    cursor: pointer;
    position: relative;
    z-index: 999;
  }

  .min {
    display: block;
  }
  .wxText {
    display: flex;
    flex-direction: row;
  }
</style>
